<template>
  <div>
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/main' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card class="box-card">
      <el-button type="primary" @click="roleAddDialog = true"
        >添加用户</el-button
      >
    </el-card>
    <el-table :data="roles" style="width: 100%" border stripe>
      <el-table-column type="expand">
        <template slot-scope="{ row }">
          <el-row
            :class="['bdrbottom', 'vmiddle']"
            v-for="item in row.children"
            :key="item.id"
          >
            <el-col :span="5">
              <el-tag closable @close="deltag(row,item.id)">{{ item.authName }}</el-tag>
              <i class="el-icon-caret-right" v-if="item.children.length>0"></i>
            </el-col>
            <el-col :span="19">
              <el-row
                :class="[index2 != 0 ? 'bdrtop' : '', 'vmiddle']"
                v-for="(item2, index2) in item.children"
                :key="item2.id"
              >
                <el-col :span="6">
                  <el-tag closable @close="deltag(row,item2.id)" type="success">{{ item2.authName }}</el-tag>
                  <i class="el-icon-caret-right" v-if="item.children.length>0"></i>
                </el-col>
                <el-col :span="18">
                  <el-tag
                    closable
                    @close="deltag(row,item3.id)"
                    type="warning"
                    v-for="item3 in item2.children"
                    :key="item3.id"
                    >{{ item3.authName }}</el-tag
                  >
                </el-col>
              </el-row>
            </el-col>
          </el-row>
        </template>
      </el-table-column>
      <el-table-column label="#" type="index" width="50px"> </el-table-column>
      <el-table-column label="角色名称" prop="roleName" width="343px">
      </el-table-column>
      <el-table-column label="角色描述" prop="roleDesc" width="500px">
      </el-table-column>
      <el-table-column label="操作" width="300px">
        <template slot-scope="{ row }">
          <el-button
            type="primary"
            size="small"
            @click="
              roleEditDialog = true;
              edit(row.id);
            "
            ><i class="el-icon-edit"></i>编辑</el-button
          >
          <el-button type="danger" size="small" @click="del(row.id)"
            ><i class="el-icon-delete"></i>删除</el-button
          >
          <el-button type="warning" size="small" @click="showAuthtree(row)"
            ><i class="el-icon-setting"></i>分配权限</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <!-- 添加对话框 -->
    <el-dialog title="添加角色" :visible.sync="roleAddDialog" width="60%">
      <el-form
        :model="addform"
        :rules="addRules"
        label-width="80px"
        ref="addForm"
      >
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="addform.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="addform.roleDesc"></el-input>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="roleAddDialog = false">取 消</el-button>
        <el-button
          type="primary"
          @click="
            roleAddDialog = false;
            sure();
          "
          >确 定</el-button
        >
      </span>
    </el-dialog>
    <!-- 编辑对话框 -->
    <el-dialog title="添加角色" :visible.sync="roleEditDialog" width="60%">
      <el-form :model="editform" label-width="80px">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="editform.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="editform.roleDesc"></el-input>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="roleAddDialog = false">取 消</el-button>
        <el-button
          type="primary"
          @click="
            roleEditDialog = false;
            editsure();
          "
          >确 定</el-button
        >
      </span>
    </el-dialog>
    <!-- 分配权限对话框 -->
    <el-dialog
      title="提示"
      :visible.sync="treeVisible"
      width="30%"
    >
      <el-tree ref="authTree" :default-checked-keys="defaultChecked" :data="authData" show-checkbox default-expand-all node-key="id" :props="{label:'authName'}">
      </el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="treeVisible = false;closeAuthtree()">取 消</el-button>
        <el-button type="primary" @click="treeVisible = false;addAuths()"
          >确 定</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>
  <script>
export default {
  data() {
    return {
      // 添加开关
      roleAddDialog: false,
      // 编辑开关
      roleEditDialog: false,
      // 权限开关
      treeVisible:false,
      // 权限列表
      authData:[],
      // 默认选中的权限id
      defaultChecked:[],
      // 当前选中的角色id
      roleId:0,
      // 添加表单
      addform: {
        roleName: "",
        roleDesc: "",
      },
      // 修改表单
      editform: {
        roleId: "",
        roleName: "",
        roleDesc: "",
      },
      query: {
        //查询
        query: "",
        //每页几条
        pagesize: 5,
        //当前第几页
        pagenum: 1,
      },
      total: 0,
      // 角色列表
      roles: [],
      // 添加表单验证规则
      addRules: {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
        ],
        password: [{ required: true, message: "请输入密码", trigger: "blur" }],
      },
    };
  },
  methods: {
    // 打开权限对话框
    showAuthtree(row){
      this.treeVisible = true;
      this.getAuths();
      // 打开对话框时，讲当前要 分配权限的角色id 保存起来，在确定添加权限时，需要用到
      this.roleId = row.id
      row.children.forEach(child=>{
        this.getTreeNids(child,this.defaultChecked)
      })
    },
    // 添加权限分配
    async addAuths(){
      const checkedKeys = [...this.$refs.authTree.getCheckedKeys(),...this.$refs.authTree.getHalfCheckedKeys()];
      console.log(checkedKeys);
      if(checkedKeys.length==0) return this.$message.error('请选择要分配的权限');
      // 发送请求
      const {data:{meta}} = await this.$http.post(`roles/${this.roleId}/rights`,{rids:checkedKeys.join(',')})
      console.log(meta);
      if(meta.status!==200) return this.$message.error('分配权限失败')
      this.$message.success('分配权限成功')
      this.list();
      this.treeVisible = false;
      this.defaultChecked=[]
    },
    // 删除角色指定权限
    deltag(row,rid){
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async () => {
          const {data:{data,meta}} = await this.$http.delete(`roles/${row.id}/rights/${rid}`);
          if(meta.status!==200) return this.$message.error('删除权限失败')
          this.$message.success('删除权限成功')
          row.children=data;
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });          
        });


    },
    // 获取属性数据中所有的权限id
    getTreeNids(treeData,arr){
      if(!treeData.children)return arr.push(treeData.id);
      treeData.children.forEach((child)=>{
        this.getTreeNids(child,arr);
      })
    },
    // 添加角色
    async sure() {
      const {
        data: { data, meta },
      } = await this.$http.post("roles", this.addform);
      if (meta.status != 201) return this.$message.error("添加角色失败");
      this.$message.success("添加角色成功");
      // this.addform.roleName='';
      // this.addform.roleDesc='';
      this.list();
    },
    // 角色列表
    async list() {
      const {data:{data,meta},} = await this.$http.get("roles");
      if(meta.status!==200) return this.$message.error('获取角色列表失败')
      this.roles = data;
    },
    // 权限列表
    async getAuths(){
      const {data:{data,meta}} = await this.$http.get('rights/tree')
      if(meta.status!==200) return this.$message.error('获取权限列表失败')
      console.log(data);
      this.authData = data
    },
    // 删除
    async del(id) {
      const{data:{meta},} = await this.$http.delete(`roles/${id}`);
      if (meta.status != 200) return this.$message.error("删除角色失败");
      this.$message.success("删除角色成功");
      this.list();
    },
    // 修改前的元数据
    async edit(id) {
      const {data:{data,meta},} = await this.$http.get(`roles/${id}`, this.editform);
      if (meta.status != 200) return this.$message.error("获取元数据失败");
      this.editform.roleId = data.roleId;
      this.editform.roleName = data.roleName;
      this.editform.roleDesc = data.roleDesc;
    },
    // 修改成功
    async editsure(id) {
      const {
        data: { data, meta },
      } = await this.$http.put(`roles/${this.editform.roleId}`, this.editform);
      if (meta.status != 200) return this.$message.error("修改角色失败");
      this.$message.success("删除角色成功");
      this.list();
    },
  },
  created() {
    this.list();
  },
};
</script>
<style lang="less" scoped>
.el-tag {
  margin: 7px;
}
.bdrbottom {
  border-bottom: 1px solid #eee;
}
.bdrtop {
  border-top: 1px solid #eee;
}
.vmiddle {
  display: flex;
  align-items: center;
}
.demo-table-expand {
  font-size: 0;
}
.demo-table-expand label {
  width: 90px;
  color: #99a9bf;
}
.demo-table-expand .el-form-item {
  margin-right: 0;
  margin-bottom: 0;
  width: 50%;
}
</style>